﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;


/// <summary>
/// 리소스 기본형
/// </summary>
public abstract class BaseResource
{
	// Members

	//bool			m_isLoaded;
	string			m_path;
	object			m_resRef;

	/// <summary>
	/// 리소스 레퍼런스
	/// </summary>
	/// <value>The resource.</value>
	protected object resource
	{
		get
		{
			if(m_resRef == null)				// * 레퍼런스가 없을 때마다 Load를 시도해봄
				Load();

			return m_resRef;
		}
		set
		{
			m_resRef	= value;
		}
	}

	public BaseResource(string path)
	{
		m_path		= path;
		Load();									// 생성할 시 최초 한번은 로드를 시도
	}

	/// <summary>
	/// 리소스를 로드한다
	/// </summary>
	public void Load()
	{
		m_resRef	= LoadResource(m_path);
		if(m_resRef == null)
		{
			Debug.LogWarning("Resource load failure : " + m_path);
		}
	}
	/// <summary>
	/// 리소스 언로드
	/// </summary>
	public void Unload()
	{
		UnloadResource(m_resRef);
		m_resRef	= null;
	}

	/// <summary>
	/// 유저가 오버라이드하는 리소스 로드 루틴
	/// </summary>
	/// <param name="path">Path.</param>
	protected abstract object LoadResource(string path);
	/// <summary>
	/// 유저가 오버라이드하는 리소스 언로드 루틴
	/// </summary>
	/// <param name="resRef">Res reference.</param>
	protected abstract void UnloadResource(object resRef);
}

public abstract class BaseResource<T> : BaseResource
{
	public new T resource
	{
		get
		{
			return (T)base.resource;
		}
		protected set
		{
			base.resource	= value;
		}
	}

	public static implicit operator T(BaseResource<T> res)
	{
		return res.resource;
	}

	public BaseResource(string path) : base(path) { }
}

/// <summary>
/// 리소스 로딩/관리
/// </summary>
public class ResourceDepot
{
	// Members

	//static Dictionary<string, BaseResource>	s_resDict;
	static Dictionary<string, object>	s_resDict;


	/// <summary>
	/// static 초기화
	/// </summary>
	static ResourceDepot()
	{
		//s_resDict	= new Dictionary<string, BaseResource>();
		s_resDict	= new Dictionary<string, object>();
	}

	/// <summary>
	/// 리소스 로드
	/// </summary>
	/// <param name="path">Path.</param>
	/// <typeparam name="T">The 1st type parameter.</typeparam>
	//public static BaseResource<T> Load<T>(string path)
	public static T Load<T>(string path)
	{
		if(!s_resDict.ContainsKey(path))				// * 딕셔너리에 없는 경우에만 생성하기
		{
			//s_resDict[path]	= ResourceDefs.LoadWrappedResource<T>(path);
			s_resDict[path]	= Resources.Load(path);

			if(s_resDict[path] == null)
			{
				Debug.LogWarning("Resource load failure : " + path);
			}
		}

		return (T)s_resDict[path];
	}
}
